import { Dialog} from '@lowcode/jpaas-common-lib'

import {I18Parse} from '@lowcode/jpaas-common-lib';
import apiFormCoreLang from '../../../locales/lang/impl/form/apiFormCoreLang';
let lang = apiFormCoreLang;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang.apiFormCore,langKey, text);
}

export default  {
    data(){
        return {
                /*commonJsLib:{
                    name: i18n('insertFunc','插入函数'),
                    children: [
                        {name: i18n('insertScript','插入调用脚本'), clickEvent: "insertInvokePcScript"},
                        {name: i18n('insertUtilScript','插入Util工具类'), clickEvent: "insertUtilScript"},
                        {name: i18n('insertCustomQuery','插入自定义查询'), clickEvent: "insertPcCustomQuery"},
                        {name: i18n('insertInterface','插入第三方接口'), clickEvent: "insertInvokePcInterface"},
                        {name: i18n('insertOpenForm','插入打开表单'), clickEvent: "insertOpenFormScript"},
                        {name: i18n('insertOpenNewTabForm','插入页签打开表单'), clickEvent: "insertOpenNewTabFormScript"},
                        {name: i18n('ajaxPostJson','AJAX请求(postJson)'), clickEvent: "insertPostJson"},
                        {name: i18n('ajaxGet','AJAX请求(get)'), clickEvent: "insertGet"},
                        {name: i18n('ajaxPostForm','AJAX请求(postForm)'), clickEvent: "insertPostForm"},
                        {name: i18n('insertCustomForm','插入打开定制页面'), clickEvent: "insertCustomForm"},
                        {name: i18n('insertVueComponent','插入打开VUE组件'), clickEvent: "insertVueComponent"},
                        {name: i18n('insertOpenList','插入打开列表'), clickEvent: "insertOpenList"},
                        {name: i18n('insertOpenDialog','插入打开对话框'), clickEvent: "insertOpenDialog"},
                        {name: i18n('insertOpenUserDialog','插入用户对话框'), clickEvent: "insertOpenUserDialog"},
                    ]
                },*/
                commonJsLib:[
                    {name: "插入调用脚本", clickEvent: "insertInvokePcScript"},
                    {name: "插入自定义查询", clickEvent: "insertPcCustomQuery"},
                    {name: "插入第三方接口", clickEvent: "insertInvokePcInterface"},
                    {name: "插入打开表单", clickEvent: "insertOpenFormScript"},
                    {name: "插入打开定制页面", clickEvent: "insertCustomForm"},
                    {name: "插入打开列表", clickEvent: "insertOpenList"},
                    {name: "插入打开对话框", clickEvent: "insertOpenDialog"},
                ],
                flowJsLib:{
                    name:i18n('flowFunc','流程函数'),
                    children:[
                        {
                            name:i18n('startProcess','启动流程'),
                            clickEvent:"startProcess"
                        },
                        {
                            name:i18n('saveDraft','保存草稿'),
                            clickEvent:"saveDraft"
                        },
                        {
                            name:i18n('openStartFlowDialog','通过界面启动流程'),
                            clickEvent:"openStartFlowDialog"
                        },
                    ]

                },
                tableJsLib: {
                    name: i18n('tableFunc','表格函数'),
                        children: [
                    {
                        name: i18n('insertRowSummary','插入行统计函数'),
                        condition: "",
                        clickEvent: "insertRowSummaryScript"
                    },
                    {
                        name: i18n('insertDrawSummary','插入总统计函数'),
                        condition: "",
                        clickEvent: "insertDrawSummaryScript"
                    },
                    {
                        name: i18n('insertActiveEdit','插入控制编辑函数'),
                        condition: "mdl.rowEdit=='YES'",
                        clickEvent: "insertActiveEditScript"
                    },
                    {
                        name: i18n('insertRowExpand','插入展开控制函数'),
                        condition: "",
                        clickEvent: "insertRowExpandScript"
                    },
                    {
                        name: i18n('insertRowClick','插入行点击事件'),
                        condition: "",
                        clickEvent: "insertRowClick"
                    },
                    {
                        name: i18n('insertDoubleRowClick','插入行双击事件'),
                        condition: "",
                        clickEvent: "insertDoubleRowClick"
                    },
                    {
                        name: i18n('insertGetCheckboxProps','插入选择框配置函数'),
                        condition: "",
                        clickEvent: "insertGetCheckboxPropsScript"
                    },
                    {
                        name: i18n('insertCustomCell','插入单元格合并函数'),
                        condition: "",
                        clickEvent: "insertCustomCellScript"
                    },
                    {name: i18n('insertSelectRows','插入选中的行'), clickEvent: "insertSelectRows"},
                    {name: i18n('insertRefreshData','插入刷新表格'), clickEvent: "insertRefreshData"},
                    {name: i18n('insertOnload','插入加载函数'),clickEvent: "insertOnload"}]
                }



        }
    },
    methods:{
        handInsertField(item){
            this.$refs.bodyScript.insertContent(item.value);
        },
        /**
         *  插入脚本。
         * @param item
         */
        handInsertScript(item){
            this[item.clickEvent]();
        },
        insertScript(script){
            this.$refs.bodyScript.insertContent(script);
        },
        insertImportScript( script){
            this.$refs.javaCode.insertContent(script);
        },
        insertInvokePcScript() {
            var self_ = this;
            this.insertInvokeScript(function (script) {
                self_.insertScript(script);
            })
        },
        insertUtilScript(){
            var str = `
            /**
            `+this.i18n("","示例 关闭页面，把选中的行数据返回")+`
            var rows=this.table.getSelectedRows();
            this.getUtil().closeWindow(this,"ok",rows);
             */
            var util=this.getUtil();
            `;
            this.insertScript(str);
        },
        insertInvokeScript(callback) {
            Dialog.openInvokeScriptDialog({
                curVm: this,
                widthHeight: ['800px', '600px']
            }, function (self, data) {
                var ary = JSON.parse(data.params);
                var paramValue = self.getParamValue(ary, false);
                var tmp = paramValue.tmp;
                var strTmp = paramValue.strTmp;
                let isSuccess = i18n('isSuccess','是否执行成功');
                let message = i18n('message','提示信息');
                let scriptReturnData = i18n('scriptReturnData','脚本返回数据')


                var str = "/**\n" +
                    strTmp +
                    " * @return " + data.descp + "\n" +
                    " */\n";
                if (data.async) {
                    str += "this.invokeScript(\"" + data.alias + "\"," + JSON.stringify(tmp) + ",function(data){\n";
                    str += "   //data:{success:"+isSuccess+",message:"+message+",data:"+scriptReturnData+"}\n";
                    str += "});"
                } else {
                    str += "//rtn:{success:"+isSuccess+",message:"+message+",data:"+scriptReturnData+"}\n";
                    str += "var rtn= this.invokeScriptPromise(\"" + data.alias + "\"," + JSON.stringify(tmp) + ");";
                }
                if (callback) {
                    callback(str);
                }
            })
        },
        getParamValue(ary, isChild) {
            var tmp = {};
            var strTmp = "";
            for (var i = 0; ary && i < ary.length; i++) {
                var obj = ary[i];
                var paramType = obj.paramType;
                if (isChild) {
                    strTmp += " *  @subParam ";
                } else {
                    strTmp += " * @param ";
                }
                strTmp += obj.paramName + " " + obj.paramDescp + " " + obj.paramType + "\n";
                if (!paramType || paramType == 'string') {
                    tmp[obj.paramName] = "";
                } else if (paramType == 'int') {
                    tmp[obj.paramName] = 0;
                } else if (paramType == 'date') {
                    tmp[obj.paramName] = null;
                } else if (paramType == 'boolean') {
                    tmp[obj.paramName] = false;
                } else if (paramType == 'obj') {
                    var child = obj.children;
                    var paramValue = this.getParamValue(child, true);
                    tmp[obj.paramName] = paramValue.tmp;
                    strTmp += paramValue.strTmp;
                }
            }
            return {
                tmp: tmp,
                strTmp: strTmp
            };
        },
        insertCustomQuery(callback) {
            Dialog.openCustomDataDialog({
                curVm: this,
                widthHeight: ['800px', '600px']
            }, function (self, data) {
                var whereField = self.getWhereField(JSON.parse(data.whereField));
                var resultField = self.getResultField(JSON.parse(data.resultField));
                var str = "\n/**\n" +
                    whereField.strTmp +
                    " */ \n" +
                    "this.invokeCustomQuery(\"" + data.key + "\"," + JSON.stringify(whereField.tmp) + ",function(data){\n" +
                    "   //"+i18n('returnData','返回的数据')+" data:[" + resultField + "]\n" +
                    "});";

                if (callback) {
                    callback(str);
                }

            });
        },
        //获取自定义查询条件字段
        getWhereField(ary) {
            let tmp = {};
            let strTmp = " * @param ";
            for (let i = 0; ary && i < ary.length; i++) {
                let obj = ary[i];
                let paramType = obj.columnType;
                strTmp += obj.fieldName + " " + paramType + "\n";
                tmp[obj.fieldName] = "";
            }
            return {
                tmp: tmp,
                strTmp: strTmp
            };
        },
        //获取自定义查询返回字段
        getResultField(ary) {
            let str = "{";
            for (let i = 0; ary && i < ary.length; i++) {
                if (i > 0) {
                    str += ",";
                }
                let obj = ary[i];
                str += obj.fieldName;
            }
            str += "}";
            return str;
        },
        insertPcCustomQuery() {
            var self_ = this;
            this.insertCustomQuery(function (script) {
                self_.insertScript(script);
            })
        },
        insertOnload(){
            let script=`onload_(){}`;
            this.insertScript(script);
        },
        insertInvokePcInterface() {
            var self_ = this;
            this.insertInvokeInterface(function (script) {
                self_.insertScript(script);
            })
        },
        insertInvokeInterface(callback) {
            Dialog.openSysInterfaceDialog({
                curVm: this, max: true
            }, function (self, data) {
                var params = {};
                var strTmp = "";
                if ((data.apiDataType == 'form' || data.apiDataType == 'json') && data.apiBody) {
                    //请求体参数配置
                    strTmp += self.getInterfaceParams(params, 'bodys', i18n('bodys','请求体'), data.apiBody, data.apiDataType == 'json');
                }
                if (data.apiHeaders) {
                    //请求头参数配置
                    strTmp += self.getInterfaceParams(params, 'headers', i18n('headers','请求头'), data.apiHeaders, false);
                }
                if (data.apiPathParams) {
                    //请求路径参数配置
                    strTmp += self.getInterfaceParams(params, 'pathParams', i18n('pathParams','路径参数'), data.apiPathParams, false);
                }
                if (data.apiQuery) {
                    //查询参数配置
                    strTmp += self.getInterfaceParams(params, 'querys', i18n('querys','查询参数'), data.apiQuery, false);
                }
                var str = "\n/**\n" +
                    i18n('apiName','接口名称') + data.apiName + "\n" +
                    i18n('apiPath','接口路径') + data.apiPath + "\n" +
                    strTmp +
                    " */ \n" +
                    "this.invokeInterface(\"" + (data.apiKey || data.apiId) + "\"," + JSON.stringify(params) + ",function(data){\n" +
                    "   //data:"+i18n('apiReturn','接口返回数据')+"\n" +
                    "});";
                if (callback) {
                    callback(str);
                }
            })
        },
        getInterfaceParams(rootParams, key, name, paramsStr, isJson) {
            var params = JSON.parse(paramsStr);
            if (isJson) {
                var getParams = function (array) {
                    return array.filter(function (item) {
                        if (item.paramType == 'object' || item.paramType == 'array') {
                            item.children = getParams(item.children);
                            return item.children.length > 0;
                        } else {
                            return item.paramSource == 'param';
                        }
                    })
                }
                let filterArr = getParams(params);
                if (filterArr.length > 0) {
                    var getParamsValue = function (obj) {
                        if (obj.paramType == 'object') {
                            var paramsValue = {};
                            for (var i = 0; i < obj.children.length; i++) {
                                var item = obj.children[i];
                                paramsValue[item.paramName] = getParamsValue(item);
                            }
                            return paramsValue;
                        } else if (obj.paramType == 'array') {
                            var paramsValue = [];
                            for (var i = 0; i < obj.children.length; i++) {
                                var item = obj.children[i];
                                paramsValue.push(getParamsValue(item));
                            }
                            return paramsValue;
                        } else {
                            if (obj.paramType == 'number') {
                                return 0;
                            } else if (obj.paramType == 'boolean') {
                                return false;
                            } else {
                                return "";
                            }
                        }
                    }
                    rootParams[key] = getParamsValue(filterArr[0]);
                    return " @param " + key + " " + name + "\n";
                }
            } else {
                let filterArr = params.filter(item => item.paramSource == 'param');
                if (filterArr.length > 0) {
                    rootParams[key] = {};
                    filterArr.map(item => {
                        rootParams[key][item.paramName] = "";
                    });
                    return " @param " + key + " " + name + "\n";
                }
            }
            return "";
        },
        insertOpenFormScript(){
            var config={
                curVm: this, widthHeight: ['900px', '600px'],
                data:{params:{}}
            };

            Dialog.openFormDialog(config,(res)=>{
                let script=`let self_=this;
            var conf={
                //${i18n('formTitle','表单标题')}
                title:"${res.name}",
                //${i18n('formSolutionAlias','表单方案别名')}
                alias:"${res.alias}",
                //${i18n('primaryKey','主键')}
                pkId:"",
                //${i18n('readonlyNote', ['{','}','{}'])}
                readOnly:false,
                parent:{},
                //${i18n('openFormDesc','open在“新页面”模式下打开表单的方式')}
                open:'window',
                //${i18n('initFormData','表单初始化数据')}
                params:{"key":"value"},
                destroy:function (action,data) {
                    //${i18n('refreshTable','刷新表格')}
                    self_.loadData();
                }
            };
            this.showForm(conf);
            `;
                this.insertScript(script);
            })
        },
        insertOpenNewTabFormScript(){
            var config={
                curVm: this, widthHeight: ['900px', '600px'],
                data:{params:{}}
            };

            Dialog.openFormDialog(config,(res)=>{
                let script=`
                let script=\`let self_=this;
            var conf={
                //${i18n('formTitle','表单标题')}
                title:"${res.name}",
                //${i18n('formSolutionAlias','表单方案别名')}
                alias:"${res.alias}",
                //${i18n('primaryKey','主键')}
                pkId:"",
                //${i18n('readonlyNote', ['{','}','{}'])}
                readOnly:false,
                parent:{},
                //${i18n('openFormDesc','open在“新页面”模式下打开表单的方式，\'window\'弹窗打开，不填或者其它则为新页面打开')}
                open:'window',
                //${i18n('initFormData','表单初始化数据')}
                params:{"key":"value"},
                destroy:function (action,data) {
                    //${i18n('refreshTable','刷新表格')}
                    self_.loadData();
                }
            };
            this.openNewTabForm(conf);`;
                this.insertScript(script)});
        },
        insertPostJson(){
            let script=`
//${i18n('insertFuncDesc1','插入postJson函数')}
let params={key:"",}
this.getAjax().postJson(url,params).then(res=>{})`;
            this.insertScript(script);
        },
        insertGet(){
            let script=`
//${i18n('insertFuncDesc2','插入get函数,参数可以为空')}
let params={key:""}
this.getAjax().get(url,params).then(res=>{})`;
            this.insertScript(script);
        },
        insertPostForm(){
            let script=`
//${i18n('insertFuncDesc2','插入get函数,参数可以为空')}
let params={key:""}
this.getAjax().postForm(url,params).then(res=>{})`;
            this.insertScript(script);
        },
        insertCustomForm(){

            var config={
                curVm: this, widthHeight: ['900px', '600px'],
            };
            Dialog.openCustomPageDialog(config,(res)=>{
                let json={};
                let paramDef=res.params || "[]";
                let paramsAry=JSON.parse(paramDef);
                for(let i=0;i<paramsAry.length;i++){
                    let o=paramsAry[i];
                    json[o.value]=o.label;
                }
                let str=JSON.stringify(json);

                let script=`let params=${str};
                this.openCustom("${res.alias}",params)`;
                this.insertScript(script);
            });
        },
        insertVueComponent(){
            let script=`var conf={
        //${i18n('componentPath','组件路径')}
        component:"modules/demo/DemoForm.vue",
        max:false,
        widthHeight:[  '800px',   '600px'],
        curVm: this,
        //${i18n('param','参数')}
        data:{"user":{name:"老周"}}
    };
    this.openComponent(conf, function(action,data){
        console.info(action,data);
    })`;
            this.insertScript(script);
        },
        getParams(searchJson){
            let params={};
            if(!searchJson){
                return params;
            }
            let json=JSON.parse(searchJson);
            let aryJson=json.filter(item=>{
                return item.type=="income";
            });
            if(aryJson.length==0){
                return params;
            }
            for(let i=0;i<aryJson.length;i++){
                let obj=aryJson[i];
                var tabPre=obj.tablePre ? obj.tablePre +"." : "";
                var type=this.getType(obj.dataType);
                var val="Q_" + tabPre + obj.fieldName +"_" +type +"_" +obj.fieldOp;
                params[val]="";
            }
            return params;
        },
        getType(type){
            var typeObj={string:"S",number:"I",date:"D"};
            if(typeObj[type]){
                return typeObj[type];
            }
            return  "S";
        },
        objToQuery(obj){
            let ary=[];
            for(let key in obj){
                ary.push(key +"=" + obj[key])
            }
            return ary.join("&");
        },
        insertOpenDialog(){
            let self_=this;
            Dialog.openFormBoListDialog({
                curVm: this,
                data: {single: true, isDialog: 'YES',isDataGrant:true},
                widthHeight: ['1000px', '600px']
            }, function (self, data,pmtAlias) {
                var obj=data[0];
                let params={single:obj.multiSelect=="NO"};
                if(pmtAlias){
                    params.pmtAlias=pmtAlias;
                }
                let searchJson=obj.searchJson;
                let objParams=self_.getParams(searchJson);
                objParams =Object.assign(params,objParams);
                let strParams=self_.objToQuery(objParams);

                var str = `/**
                    ${i18n('openDialog','打开对话框：')}${obj.name} 
                     */
                    this.getDialog().dialog({key:"${obj.key}",params:"${strParams}",onload:function(){
                      this.$nextTick(() => {
                        let isDialog = this.formBoList.isDialog;
                        let isTreeDlg = this.formBoList.isTreeDlg;
                        let multiSelect = this.formBoList.multiSelect;
                        let idField = this.formBoList.idField;
                        setTimeout(() => {
                        let returnData=[];
                        if (isTreeDlg === 'YES') {
                           let ary=returnData.map(item=>item[idField])
                           this.$refs.rxTree.checkeds=ary;
                        } else if (isDialog === 'YES') {
                           this.selectedRows=returnData;
                           if (multiSelect){
                              this.selectedTable.dataSource=[...returnData]
                           }
                        }
                        });
                      });
                    }},
                    {curVm: this,max:${obj.isMax=="YES"},widthHeight:['${obj.width}px', '${obj.height}px']},function(data){
                        //data:${i18n('selectDialogData','对话框选择数据')}
                    })`;

                self.insertScript(str);
            })
        },
        insertOpenUserDialog(){
            let script=`
                let config={
                curVm:this,
                widthHeight:['1000px','600px'],
                max:false,
                data:{
                    showDimId:false,
                    initUsers:[{userId:'1',fullName:'管理员'}],

                }
            };
            this.getDialog().openUserDialog(config,function(vm,data){
                console.info(data);
            })  `;
            return  this.insertScript(script);;
        },
        insertOpenList(){
            let self_=this;
            Dialog.openFormBoListDialog({
                curVm: this,
                data: {single: true, isDialog: 'NO',isDataGrant:true},
                widthHeight: ['1000px', '600px']
            }, function (self, data,pmtAlias) {

                var obj=data[0];

                let params={single:obj.multiSelect=="NO"};
                if(pmtAlias){
                    params.pmtAlias=pmtAlias;
                }
                let searchJson=obj.searchJson;
                let objParams=self_.getParams(searchJson);
                objParams =Object.assign(params,objParams);
                let strParams=self_.objToQuery(objParams);

                var str = `/**
                    ${i18n('openList','打开列表：')}${obj.name} 
                     */
                    this.getDialog().dialog({key:"${obj.key}",params:"${strParams}"},
                    {curVm: this,max:${obj.isMax=="YES"},widthHeight:['${obj.width}px', '${obj.height}px']},function(data){
                        //data:${i18n('selectDialogData','对话框选择数据')}
                    })`;
                self.insertScript(str);
            })
        },
        startProcess(){
            let script=`let json={"${i18n('formAlias','表单别名')}":"${i18n('formAliasValue','表单JSON数据,是JSON对象')}"}
    let params={
        formJson:JSON.stringify(json),
        //${i18n('draftInstance','草稿实例')}
        instId:"",
        defKey:"${i18n('processDefKey','流程定义KEY')}"
    }
    this.startProcess(params).then(res=>{})`;
            this.insertScript(script);
        },
        saveDraft(){
            let script=`let json={"${i18n('formAlias','表单别名')}":"${i18n('formAliasValue','表单JSON数据,是JSON对象')}"}
    let params={
        formJson:JSON.stringify(json),
        //${i18n('draftInstance','草稿实例')}
        instId:"",
        defKey:"${i18n('processDefKey','流程定义KEY')}"
    }
    this.saveDraft(params).then(res=>{})`;
            this.insertScript(script);
        },
        openStartFlowDialog(){
            let script=`this.openStartFlowDialog("${i18n('processAlias','流程别名')}","${i18n('formPrimaryKey','表单主键')}",{${i18n('formKeyValue','表单数据可以为null')}},function(action,data){
    })`;
            this.insertScript(script);
        },
        insertCustomCellScript(){
            let script=`customCell(field,row,index,data){
        //${i18n('customCellDesc1','field:列名 row:行数据,index:行下标,data:表格对象')}
        //this.getRowSpan(field,row,index,data.data) :${i18n('customCellDesc2','获取当前列可以纵向合并的数量')}
        //this.getColSpan(field,row,data) :${i18n('customCellDesc3','获取当前列可以横向合并的数量')}
        const obj = {
          attrs: {},
        };
        return obj;
      }`;
            this.insertScript(script);
        },
        insertRowSummaryScript(){
            let script=`rowSummaryFun(record){
        //${i18n('insertScriptDesc1','返回一行数据到子节点')}
        return {};
      }`;
            this.insertScript(script);
        },
        insertDrawSummaryScript(){
            let script=`drawSummaryFun(e){
        //${i18n('insertScriptDesc2','赋值e.cellHtml来展示统计行内容')}
        //e:{sender,data,column,field,cellHtml,width}
        }`;
            this.insertScript(script);
        },
        insertActiveEditScript(){
            let script=`activeEditFun(col,row){
        //${i18n('insertScriptDesc3','返回true/false，来确定单元格是否可编辑')}
        //col:{column,index} row:{record,index}
        }`;
            this.insertScript(script);
        },
        insertRowExpandScript(){
            let script=`
            //${i18n('insertScriptDesc4','行展开函数')}
            rowExpand(expanded,record) {
      
      }`;
            this.insertScript(script);
        },
        insertGetCheckboxPropsScript(){
            let script=`getCheckboxPropsMethod(record){
        return ({
                    props: {
                        disabled: true
                    }
                })
        }`;
            this.insertScript(script);
        },
        insertRowClick(){
            let script=`//${i18n('insertClickDesc1','插入行点击函数')}
handRowClick(record, index){
}`;
            this.insertScript(script);
        },
        insertDoubleRowClick(){
            let script=`
//${i18n('insertClickDesc2','插入行双击函数')}
handRowDblClick(record,index){
}`;
            this.insertScript(script);
        },
        insertSelectRows(){
            let script=`this.table.getSelectedRows()`;
            this.insertScript(script);
        },
        /**
         * 插入刷新方法。
         */
        insertRefreshData(){
            let script=`this.loadData()`;
            this.insertScript(script);
        },
    }

}